package com.xunjing.order.config.sharding;

import com.xunjing.common.core.utils.DateUtils;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.util.Collection;

/**
 * @Author ZYT
 * @Date 2024-03-29 18:11
 * @Version 1.0
 * @Describe 精确分片算法(用作数据插入)
 */
@Component
public class DatePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Timestamp> {

    private static ShardingAlgorithmReload shardingAlgorithmReload;
    @Autowired
    public void setShardingAlgorithmReload(ShardingAlgorithmReload shardingAlgorithmReload){
        DatePreciseShardingAlgorithm.shardingAlgorithmReload = shardingAlgorithmReload;
    }


    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Timestamp> preciseShardingValue) {
        //在使用Sharding时，preciseShardingValue的值被解释为 java.sql.Timestamp 而不是 java.time.LocalDateTime，需要转换
        Timestamp timestamp =  preciseShardingValue.getValue();
        //组合真正的表名
        String preciseTable = preciseShardingValue.getLogicTableName() + "_" + DateUtils.timestampToStr(timestamp,"yyyyMM");
        //判断缓存里是否包含分表
        if(collection.contains(preciseTable)){
            return preciseTable;
        }else{
            // 检查分表获取的表名不存在，需要自动建表
            boolean isSuccess = shardingAlgorithmReload.createShardingTable(preciseShardingValue.getLogicTableName(), preciseTable);
            if (isSuccess) {
                //添加缓存
                collection.add(preciseTable);
                //重载缓存
                //shardingAlgorithmReload.tableNameCacheReloadAll();
                return preciseTable;
            } else {
                // 如果建表失败，返回逻辑空表(无法插入数据)
                throw new IllegalArgumentException("未找到匹配的数据表");
            }
        }
    }
}


